/**
 * coder:yeates
 */
(function(){
	var Model=function(canvas){
		var me = this;
		
		me.puppleArr = [];		//泡泡的数组对象
		
		me.puppleNum = 250;		//炮炮的个数
		
		me.canvas = canvas;
		me.context = canvas.getContext('2d');			//绘图功能由绘图上下文来控制，即context
		
		//添加泡泡到泡泡数组之中
		for(var i = 0; i < me.puppleNum; i++){
			me.puppleArr.push(me.genPupple());	
		}
		
		//让泡泡动起来
		me.shake();		
		
	}
	
	/**
	 * 作用：产生泡泡
	 * prototype是圆形扩展，genPupple是名字
	 */
	Model.prototype.genPupple=function(){
		return{
			radius: (Math.random() * 15 | 0) || 1,	//球半径
			v: Math.random() * 100,
			r: 255,
			g: Math.random() * 100 | 0,
			b: Math.random() * 100 | 0,
			a: Math.random(),						//透明度
			angle: Math.PI * Math.random() * 2,		//保证360度发射
			x: this.canvas.width / 2,
			y: this.canvas.height / 2
		}
	}
	
	/**
	 * 作用：让泡泡动起来
	 */
	Model.prototype.shake = function(){
		var me = this;
		var ctx = me.context;		//画图场景的上下文
		
		foo();
		function foo(){
			ctx.clearRect(0,0,me.canvas.width, me.canvas.height);
			for(var i = 0; i < me.puppleArr.length; i++){
				var o = me.puppleArr[i];
				ctx.fillStyle = 'rgba(' + o.r + ',' + o.g + ',' + o.b + ',' + o.a + ')';
				ctx.beginPath();
				ctx.arc(o.x, o.y, o.radius, 0, 360, false);
				ctx.fill();
				ctx.closePath();
				
				o.x += (o.v * 0.03) * Math.cos(o.angle);
				o.y += (o.v * 0.03) * Math.sin(o.angle);
				o.a += 0.01;
				if(o.b < 255 && o.g < 255 && o.r == 255){
					o.b+=1;
				}
				else if(o.b >= 250 && o.g < 255){
					o.g+=1;
					o.r-=1;
				}
				else if(o.r <= 255){
					o.b+=1;
					o.r+=1;
					o.g-=1;
				}

				//如果泡泡已经全透明了，那么就新建一个泡泡来代替这个泡泡
				if(o.x > me.canvas.width || o.y > me.canvas.height || o.x <= 0 || o.y <= 0){
					o = me.genPupple();
					me.puppleArr.splice(i,1);
					me.puppleArr.push(o);

				}
			}
			setTimeout(foo, 30);
		}
		
	}
	
	window.Pupple = Model;
}());
